﻿using Aspose.Hook;
using Aspose.Words;
using Aspose.Words.Fields;
using Aspose.Words.Reporting;
using Aspose.Words.Tables;
using Newtonsoft.Json.Linq;
using NUnit.Framework;
using WordStudy20250123.T001;

namespace WordStudy20250123.T000
{
    [TestFixture]
    internal class TemplateTest02
    {
        [SetUp]
        public void Setup()
        {
            HookManager.ShowHookDetails(true);
            HookManager.StartHook();
        }

        [Test]
        public void Test01()
        {
            string jsonStr = "";

            string templatePath = @"D:\data\WordStudy20250123\TemplateTest01\报警与保护-模版.docx";
            string outputPath = @"D:\data\WordStudy20250123\TemplateTest01\报警与保护-文档.docx";
            jsonStr = "{"
                + "\"k4_1_01\":\"false\",\"k4_1_02\":\"true\",\"k4_1_03\":\"true\",\"k4_1_04\":\"true\",\"k4_1_05\":\"true\",\"k4_1_06\":\"true\",\"k4_1_07\":\"true\",\"k4_1_08\":\"true\",\"k4_1_09\":\"true\"," 
                + "\"k4_2_01\":\"false\",\"k4_2_02\":\"true\",\"k4_2_03\":\"true\",\"k4_2_04\":\"true\",\"k4_2_05\":\"true\",\"k4_2_06\":\"true\",\"k4_2_07\":\"true\",\"k4_2_08\":\"true\",\"k4_2_09\":\"true\"," 
                + "\"k4_3_01\":\"false\",\"k4_3_02\":\"true\",\"k4_3_03\":\"true\",\"k4_3_04\":\"true\",\"k4_3_05\":\"true\",\"k4_3_06\":\"true\",\"k4_3_07\":\"true\",\"k4_3_08\":\"true\",\"k4_3_09\":\"true\"," 
                + "\"k4_4_01\":\"false\",\"k4_4_02\":\"true\",\"k4_4_03\":\"true\",\"k4_4_04\":\"true\",\"k4_4_05\":\"true\",\"k4_4_06\":\"true\",\"k4_4_07\":\"true\",\"k4_4_08\":\"true\",\"k4_4_09\":\"true\"," 
                + "\"k4_5_01\":\"false\",\"k4_5_02\":\"true\",\"k4_5_03\":\"true\",\"k4_5_04\":\"true\",\"k4_5_05\":\"true\"," 
                + "\"k4_6_01\":\"false\",\"k4_6_02\":\"true\",\"k4_6_03\":\"true\",\"k4_6_04\":\"true\",\"k4_6_05\":\"true\"," 
                + "\"k4_8_01\":\"false\",\"k4_8_02\":\"true\",\"k4_8_03\":\"true\",\"k4_8_04\":\"true\",\"k4_8_05\":\"true\",\"k4_8_06\":\"true\",\"k4_8_07\":\"true\",\"k4_8_08\":\"true\"," 
                + "\"k4_9_01\":\"false\",\"k4_9_02\":\"true\",\"k4_9_03\":\"true\",\"k4_9_04\":\"true\",\"k4_9_05\":\"true\"," 
                + "\"k4_10_01\":\"false\",\"k4_10_02\":\"true\",\"k4_10_03\":\"true\",\"k4_10_04\":\"true\",\"k4_10_05\":\"true\"," 
                + "\"k4_12_01\":\"false\",\"k4_12_02\":\"true\",\"k4_12_03\":\"true\"," 
                + "\"k4_13_01\":\"false\",\"k4_13_02\":\"true\",\"k4_13_03\":\"true\"," 
                + "\"k4_14_01\":\"false\",\"k4_14_02\":\"true\",\"k4_14_03\":\"true\"" 
                + "}";

            //string templatePath = @"D:\data\WordStudy20250123\TemplateTest01\辅助系统检测-模版.docx";
            //string outputPath = @"D:\data\WordStudy20250123\TemplateTest01\辅助系统检测-文档.docx";
            //jsonStr = "{\"k59_1_01\":\"在这里有一段文字描述，巴拉巴拉amtf\"}";

            //string templatePath = @"D:\data\WordStudy20250123\TemplateTest01\浪涌（冲击）抗扰度-模版.docx";
            //string outputPath = @"D:\data\WordStudy20250123\TemplateTest01\浪涌（冲击）抗扰度-文档.docx";

            //string templatePath = @"D:\data\WordStudy20250123\TemplateTest01\电快速瞬变脉冲群抗扰度-模版.docx";
            //string outputPath = @"D:\data\WordStudy20250123\TemplateTest01\电快速瞬变脉冲群抗扰度-文档.docx";

            //string templatePath = @"D:\data\WordStudy20250123\TemplateTest01\射频电磁场辐射抗扰度-模版.docx";
            //string outputPath = @"D:\data\WordStudy20250123\TemplateTest01\射频电磁场辐射抗扰度-文档.docx";

            //string templatePath = @"D:\data\WordStudy20250123\TemplateTest01\静电放电抗扰度-模版.docx";
            //string outputPath = @"D:\data\WordStudy20250123\TemplateTest01\静电放电抗扰度-文档.docx";

            //string templatePath = @"D:\data\WordStudy20250123\TemplateTest01\电磁骚扰-模版.docx";
            //string outputPath = @"D:\data\WordStudy20250123\TemplateTest01\电磁骚扰-文档.docx";

            //string templatePath = @"D:\data\WordStudy20250123\TemplateTest01\结构稳定性-模版.docx";
            //string outputPath = @"D:\data\WordStudy20250123\TemplateTest01\结构稳定性-文档.docx";

            //string templatePath = @"D:\data\WordStudy20250123\TemplateTest01\外壳和支架强度-模版.docx";
            //string outputPath = @"D:\data\WordStudy20250123\TemplateTest01\外壳和支架强度-文档.docx";
            //jsonStr = "{\"k49_1_01\":\"在这里有一段文字描述，巴拉巴拉小魔仙\"}";

            //string templatePath = @"D:\data\WordStudy20250123\TemplateTest01\紫外暴露-模版.docx";
            //string outputPath = @"D:\data\WordStudy20250123\TemplateTest01\紫外暴露-文档.docx";
            //jsonStr = "{\"k48_1_01\":\"在这里有一段文字描述，巴拉巴拉变\"}";

            //string templatePath = @"D:\data\WordStudy20250123\TemplateTest01\可触及性-模版.docx";
            //string outputPath = @"D:\data\WordStudy20250123\TemplateTest01\可触及性-文档.docx";
            //jsonStr = "{\"k47_1_01\":\"在这里有一段文字描述，我的巴拉巴拉\"}";

            //string templatePath = @"D:\data\WordStudy20250123\TemplateTest01\盐雾适应性-模版.docx";
            //string outputPath = @"D:\data\WordStudy20250123\TemplateTest01\盐雾适应性-文档.docx";

            //string templatePath = @"D:\data\WordStudy20250123\TemplateTest01\湿热适应性-模版.docx";
            //string outputPath = @"D:\data\WordStudy20250123\TemplateTest01\湿热适应性-文档.docx";
            //jsonStr = "{\"k45_1_01\":\"false\",\"k45_1_02\":\"true\"}";

            //string templatePath = @"D:\data\WordStudy20250123\TemplateTest01\高温适应性-模版.docx";
            //string outputPath = @"D:\data\WordStudy20250123\TemplateTest01\高温适应性-文档.docx";

            //string templatePath = @"D:\data\WordStudy20250123\TemplateTest01\低温适应性-模版.docx";
            //string outputPath = @"D:\data\WordStudy20250123\TemplateTest01\低温适应性-文档.docx";

            //string templatePath = @"D:\data\WordStudy20250123\TemplateTest01\温升-模版.docx";
            //string outputPath = @"D:\data\WordStudy20250123\TemplateTest01\温升-文档.docx";

            //string templatePath = @"D:\data\WordStudy20250123\TemplateTest01\电容残余能量危险防护-模版.docx";
            //string outputPath = @"D:\data\WordStudy20250123\TemplateTest01\电容残余能量危险防护-文档.docx";
            //jsonStr = "{\"k41_1_01\":\"56.78\"}";

            // 处理表单数据

            if (jsonStr == null || jsonStr.Length < 1)
            {
                jsonStr = "{}";
            }
            JObject jsonObject = JObject.Parse(jsonStr);
            // 获取 Values 节点
            Dictionary<string, string> map = new Dictionary<string, string>();
            foreach (var item in jsonObject)
            {
                string key = item.Key;
                map.Add(key, item.Value.ToString());
            }

            GenerateReport(templatePath, outputPath, map);
        }

        [Test]
        public void Test02()
        {
            string imagePath = @"D:\data\WordStudy20250123\TemplateTest01\dingliren.png";
            //string filePath = @"D:\data\WordStudy20250123\TemplateTest01\报警与保护-文档.docx";
            //string outputPath = @"D:\data\WordStudy20250123\TemplateTest01\报警与保护-文档.docx";

            //string filePath = @"D:\data\WordStudy20250123\TemplateTest01\辅助系统检测-文档.docx";
            //string outputPath = @"D:\data\WordStudy20250123\TemplateTest01\辅助系统检测-文档.docx";

            //string filePath = @"D:\data\WordStudy20250123\TemplateTest01\电快速瞬变脉冲群抗扰度-文档.docx";
            //string outputPath = @"D:\data\WordStudy20250123\TemplateTest01\电快速瞬变脉冲群抗扰度-文档.docx";

            //string filePath = @"D:\data\WordStudy20250123\TemplateTest01\射频电磁场辐射抗扰度-文档.docx";
            //string outputPath = @"D:\data\WordStudy20250123\TemplateTest01\射频电磁场辐射抗扰度-文档.docx";

            //string filePath = @"D:\data\WordStudy20250123\TemplateTest01\静电放电抗扰度-文档.docx";
            //string outputPath = @"D:\data\WordStudy20250123\TemplateTest01\静电放电抗扰度-文档.docx";

            //string filePath = @"D:\data\WordStudy20250123\TemplateTest01\结构稳定性-文档.docx";
            //string outputPath = @"D:\data\WordStudy20250123\TemplateTest01\结构稳定性-文档.docx";

            //string filePath = @"D:\data\WordStudy20250123\TemplateTest01\外壳和支架强度-文档.docx";
            //string outputPath = @"D:\data\WordStudy20250123\TemplateTest01\外壳和支架强度-文档.docx";

            //string filePath = @"D:\data\WordStudy20250123\TemplateTest01\紫外暴露-文档.docx";
            //string outputPath = @"D:\data\WordStudy20250123\TemplateTest01\紫外暴露-文档.docx";

            //string filePath = @"D:\data\WordStudy20250123\TemplateTest01\可触及性-文档.docx";
            //string outputPath = @"D:\data\WordStudy20250123\TemplateTest01\可触及性-文档.docx";

            //string filePath = @"D:\data\WordStudy20250123\TemplateTest01\盐雾适应性-文档.docx";
            //string outputPath = @"D:\data\WordStudy20250123\TemplateTest01\盐雾适应性-文档.docx";

            //string filePath = @"D:\data\WordStudy20250123\TemplateTest01\湿热适应性-文档.docx";
            //string outputPath = @"D:\data\WordStudy20250123\TemplateTest01\湿热适应性-文档.docx";

            //string filePath = @"D:\data\WordStudy20250123\TemplateTest01\高温适应性-文档.docx";
            //string outputPath = @"D:\data\WordStudy20250123\TemplateTest01\高温适应性-文档.docx";

            //string filePath = @"D:\data\WordStudy20250123\TemplateTest01\低温适应性-文档.docx";
            //string outputPath = @"D:\data\WordStudy20250123\TemplateTest01\低温适应性-文档.docx";

            //string filePath = @"D:\data\WordStudy20250123\TemplateTest01\温升-文档.docx";
            //string outputPath = @"D:\data\WordStudy20250123\TemplateTest01\温升-文档.docx";

            //string filePath = @"D:\data\WordStudy20250123\TemplateTest01\电容残余能量危险防护-文档.docx";
            //string outputPath = @"D:\data\WordStudy20250123\TemplateTest01\电容残余能量危险防护-文档.docx";

            string filePath = @"D:\data\WordStudy20250123\TemplateTest01\电磁骚扰-文档.docx";
            string outputPath = @"D:\data\WordStudy20250123\TemplateTest01\电磁骚扰-文档.docx";
            WordHelper.InsertImageAtBookmark(filePath, "TestImage", imagePath, outputPath, 50, 20);
            WordHelper.InsertImageAtBookmark(filePath, "RecordImage", imagePath, outputPath, 50, 20);
            WordHelper.InsertImageAtBookmark(filePath, "CheckImage", imagePath, outputPath, 50, 20);
        }

        public static void GenerateReport(string templatePath, string outputPath, Dictionary<string, string> map)
        {
            try
            {
                // 加载模板文档
                Document doc = new Document(templatePath);

                // 准备数据
                var data = new ReportData
                {
                    ItemNo = "GB/T 34120-2023/6.2、GB/T 34133-2023/7.2",
                    ItemName = "测试项目",
                    ContractNumber = "合同编号",
                    Client = "客户名称",
                    ProductName = "产品名称",
                    ProductType = "产品类型",
                    SampleNumber = "样品编号",
                    StartTestTime = "2025-01-23",
                    StartT = "20",
                    StartH = "50",
                    StartP = "101.3",
                    EndTestTime = "2025-01-24",
                    EndT = "25",
                    EndH = "60",
                    EndP = "101.3",
                    P = 1,
                    Devices = new List<Device>
                    {
                        new Device
                        {
                            DevNo = "001",
                            DevName = "设备名称01",
                            DevType = "设备类型01",
                            ValidTime = "2025-01-02"
                        },
                        new Device
                        {
                            DevNo = "002",
                            DevName = "设备名称02",
                            DevType = "设备类型02",
                            ValidTime = "2025-01-03"
                        }
                    },
                    TestPlace = "江苏省南京市",
                    ReportTime = "2025-01-25",
                    ReportNo = "报告编号",
                    BeforeDeviceStatus = 1,
                    SampleStatusBefore = 1,
                    AfterDeviceStatus = 0,
                    SampleStatusAfter = 0,
                    ExpResult = 1,
                    TR = 1,
                    Map = map
                };

                // 创建引擎并配置
                var engine = new ReportingEngine();

                // 使用简单的数据源名称
                engine.BuildReport(doc, data, "s");

                //string PhotoPath = @"D:\data\WordStudy20250123\TemplateTest01\dingliren.png";
                //FindReplaceOptions options = new FindReplaceOptions
                //{
                //    ReplacingCallback = new ImageReplaceCallback(PhotoPath, 50, 20)
                //};
                //doc.Range.Replace(new Regex(@"\[TestImage\]"), "", options);
                //doc.Range.Replace(new Regex(@"\[RecordImage\]"), "", options);
                //doc.Range.Replace(new Regex(@"\[CheckImage\]"), "", options);


                // 删除空白页
                doc.RemoveBlankPages();
                // 调整页眉页脚边距
                //SetHeaderFotterMargin(doc);
                // 创建页眉
                CreateDocHeader(doc);
                // 创建页脚
                CreateDocFooter(doc, data.ReportTime, data.ReportNo);
                // 保存文档
                doc.Save(outputPath);
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }
        }

        public static void SetHeaderFotterMargin(Document doc)
        {
            // 1. 调整页边距
            //foreach (Section one in doc.Sections)
            //{
            //    // 减小页眉页脚的边距
            //    Console.WriteLine(one.PageSetup.HeaderDistance); // 减小页眉到正文的距离
            //    Console.WriteLine(one.PageSetup.FooterDistance); // 减小页脚到正文的距离
            //    // 如果需要，也可以调整页面边距
            //    Console.WriteLine(one.PageSetup.TopMargin);    // 上边距
            //    Console.WriteLine(one.PageSetup.BottomMargin); // 下边距
            //    Console.WriteLine(one.PageSetup.LeftMargin);   // 左边距
            //    Console.WriteLine(one.PageSetup.RightMargin);  // 右边距
            //    Console.WriteLine("====================================");
            //}

            // 1. 调整页边距
            foreach (Section one in doc.Sections)
            {
                // 减小页眉页脚的边距
                one.PageSetup.HeaderDistance = 42.55; // 减小页眉到正文的距离
                one.PageSetup.FooterDistance = 49.6; // 减小页脚到正文的距离
                // 如果需要，也可以调整页面边距
                one.PageSetup.TopMargin = 72;    // 上边距
                one.PageSetup.BottomMargin = 72; // 下边距
                one.PageSetup.LeftMargin = 90;   // 左边距
                one.PageSetup.RightMargin = 90;  // 右边距
            }
        }

        public static void CreateDocHeader(Document doc)
        {
            // 获取或创建第一个节
            Section section = doc.FirstSection;
            if (doc.Sections.Count == 0)
            {
                doc.AppendChild(new Section(doc));
                section = doc.FirstSection;
            }

            // 获取或创建页眉
            HeaderFooter header = section.HeadersFooters[HeaderFooterType.HeaderPrimary];
            if (header == null)
            {
                header = new HeaderFooter(doc, HeaderFooterType.HeaderPrimary);
                section.AppendChild(header);
            }

            // 创建3列表
            Table table = new Table(doc);
            Row row = new Row(doc);
            Cell leftCell = new Cell(doc);
            Cell centerCell = new Cell(doc);
            Cell rightCell = new Cell(doc);

            // 设置单元格边框不可见
            leftCell.CellFormat.Borders.ClearFormatting();
            centerCell.CellFormat.Borders.ClearFormatting();
            rightCell.CellFormat.Borders.ClearFormatting();

            // 左侧 STIEE
            Paragraph leftPara = new Paragraph(doc);
            Run leftRun = new Run(doc, "STIEE");
            leftRun.Font.Bold = true;
            leftPara.AppendChild(leftRun);
            leftPara.ParagraphFormat.Alignment = ParagraphAlignment.Left;
            leftCell.AppendChild(leftPara);

            // 中间 上海电器设备检测所有限公司原始记录
            Paragraph centerPara = new Paragraph(doc);
            Run centerRun = new Run(doc, "上海电器设备检测所有限公司原始记录");
            centerRun.Font.Bold = true;
            centerPara.AppendChild(centerRun);
            centerPara.ParagraphFormat.Alignment = ParagraphAlignment.Center;
            centerCell.AppendChild(centerPara);

            // 右侧页码
            Paragraph rightPara = new Paragraph(doc);
            rightPara.AppendChild(new Run(doc, "第 "));
            rightPara.AppendField(FieldType.FieldPage, true);
            rightPara.AppendChild(new Run(doc, " 页 共 "));
            rightPara.AppendField(FieldType.FieldNumPages, true);
            rightPara.AppendChild(new Run(doc, " 页"));
            rightPara.ParagraphFormat.Alignment = ParagraphAlignment.Right;
            rightCell.AppendChild(rightPara);

            // 设置单元格垂直对齐
            leftCell.CellFormat.VerticalAlignment = CellVerticalAlignment.Center;
            centerCell.CellFormat.VerticalAlignment = CellVerticalAlignment.Center;
            rightCell.CellFormat.VerticalAlignment = CellVerticalAlignment.Center;

            // 组装表格
            row.AppendChild(leftCell);
            row.AppendChild(centerCell);
            row.AppendChild(rightCell);
            table.AppendChild(row);

            // 设置列宽（根据需要调整比例）
            table.PreferredWidth = PreferredWidth.FromPercent(100);
            leftCell.CellFormat.Width = 10; // 20%
            centerCell.CellFormat.Width = 60; // 60%
            rightCell.CellFormat.Width = 30; // 20%

            // 添加表格到页眉
            header.AppendChild(table);
        }

        public static void CreateDocFooter(Document doc, string reportDate, string reportNo)
        {
            // 获取或创建第一个节
            Section section = doc.FirstSection;
            if (doc.Sections.Count == 0)
            {
                doc.AppendChild(new Section(doc));
                section = doc.FirstSection;
            }

            // 获取或创建页脚
            HeaderFooter footer = section.HeadersFooters[HeaderFooterType.FooterPrimary];
            if (footer == null)
            {
                footer = new HeaderFooter(doc, HeaderFooterType.FooterPrimary);
                section.AppendChild(footer);
            }

            // 创建两列表格
            Table table = new Table(doc);
            Row row = new Row(doc);
            Cell leftCell = new Cell(doc);
            Cell rightCell = new Cell(doc);

            // 清除表格和单元格边框
            leftCell.CellFormat.Borders.ClearFormatting();
            rightCell.CellFormat.Borders.ClearFormatting();

            // 左侧日期
            Paragraph leftPara = new Paragraph(doc);
            Run leftRun = new Run(doc, reportDate);
            leftPara.AppendChild(leftRun);
            leftPara.ParagraphFormat.Alignment = ParagraphAlignment.Left;
            leftCell.AppendChild(leftPara);

            // 右侧编号
            Paragraph rightPara = new Paragraph(doc);
            rightPara.AppendChild(new Run(doc, reportNo));
            rightPara.ParagraphFormat.Alignment = ParagraphAlignment.Right;
            rightCell.AppendChild(rightPara);

            // 设置单元格垂直对齐
            leftCell.CellFormat.VerticalAlignment = CellVerticalAlignment.Center;
            rightCell.CellFormat.VerticalAlignment = CellVerticalAlignment.Center;

            // 组装表格
            row.AppendChild(leftCell);
            row.AppendChild(rightCell);
            table.AppendChild(row);

            // 设置列宽
            table.PreferredWidth = PreferredWidth.FromPercent(100);
            leftCell.CellFormat.Width = 30;
            rightCell.CellFormat.Width = 70;

            // 添加表格到页脚
            footer.AppendChild(table);
        }
    }

    public class ReportData
    {
        public string ItemNo { get; set; }
        public string ItemName { get; set; }
        public string ContractNumber { get; set; }
        public string Client { get; set; }
        public string ProductName { get; set; }
        public string ProductType { get; set; }
        public string SampleNumber { get; set; }
        public string StartTestTime { get; set; }
        public string StartT { get; set; }
        public string StartH { get; set; }
        public string StartP { get; set; }
        public string EndTestTime { get; set; }
        public string EndT { get; set; }
        public string EndH { get; set; }
        public string EndP { get; set; }
        public int P { get; set; }
        public List<Device> Devices { get; set; }
        public string TestPlace { get; set; }
        public string ReportTime { get; set; }
        public string ReportNo { get; set; }
        public int BeforeDeviceStatus { get; set; }
        public int SampleStatusBefore { get; set; }
        public int AfterDeviceStatus { get; set; }
        public int SampleStatusAfter { get; set; }
        public int ExpResult { get; set; }
        public int TR { get; set; }
        public Dictionary<string, string> Map { get; set; }
    }

    public class Device
    {
        public string DevNo { get; set; }
        public string DevName { get; set; }
        public string DevType { get; set; }
        public string ValidTime { get; set; }
    }
}
